﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;

namespace ImageTagEditor
{
	/// <summary>
	/// Represents the margins for glass, used in translating WPF's Thickness
	/// to GlassHelper's needed margins
	/// </summary>
	[StructLayout(LayoutKind.Sequential)]
	public struct MARGINS
	{
		/// <summary>
		/// Create a new MARGINS
		/// </summary>
		/// <param name="thickness">The WPF thickness to get the margins from</param>
		public MARGINS(Thickness thickness)
		{
			Left = (int)thickness.Left;
			Right = (int)thickness.Right;
			Top = (int)thickness.Top;
			Bottom = (int)thickness.Bottom;
		}

		/// <summary>
		/// How far into the left of the window to extend the glass
		/// </summary>
		public int Left;

		/// <summary>
		/// How far into the right of the window to extend the glass
		/// </summary>
		public int Right;

		/// <summary>
		/// How far into the top of the window to extend the glass
		/// </summary>
		public int Top;

		/// <summary>
		/// How far into the bottom of the window to extend the glass
		/// </summary>
		public int Bottom;
	}

	/// <summary>
	/// Helper for WPF Windows to extend the Vista Glass chrome into the 
	/// WPF Window
	/// </summary>
	public class GlassHelper
	{

		[DllImport("dwmapi.dll", PreserveSig=false)]
		static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset);

		[DllImport("dwmapi.dll", PreserveSig=false)]
		static extern bool DwmIsCompositionEnabled();

		/// <summary>
		/// Extend the glass chrome into a WPF window
		/// </summary>
		/// <param name="window">The WPF window to extend the glass into</param>
		/// <param name="margin">The thickness on each side of the window the glass should be</param>
		/// <returns>True if glass was able to be extended, false if not</returns>
		public static bool ExtendGlassFrame(Window window, Thickness margin)
		{
			if (!DwmIsCompositionEnabled())
				return false;

			IntPtr hwnd = new WindowInteropHelper(window).Handle;
			if (hwnd == IntPtr.Zero)
			{
				throw new InvalidOperationException("Window must be shown before extending glass");
			}

			//Set the background to transparent from both the WPF and Win32 perspectives
			window.Background = Brushes.Transparent;
			HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent;

			MARGINS margins = new MARGINS(margin);

			DwmExtendFrameIntoClientArea(hwnd, ref margins);
			return true;
		}
	}
}
